<?php
/**
 * Created by 2019/4/11 0011
 * Effect: ApiBaseController.php
 * Author: 品花
 * Date: 2019/4/11 0011
 * Time: 下午 1:48
 */
namespace App\HttpController;


use App\Model\SystemConfig;
use App\Model\User;
use App\Model\UserStarCoinRecord;
use App\Utility\Response;
use App\Utility\WechatService;
use App\Validate\ValidateTool;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Http\Message\Status;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\EasySwoole\Logger;
use phpDocumentor\Reflection\DocBlock\Tags\Throws;

class BaseController extends Controller
{

    public function index()
    {
        // TODO: Implement index() method.
    }

    function onException(\Throwable $throwable): void
    {

        if(Core::getInstance()->isDev()){

            $errorMsg = "{$throwable->getMessage()}";
            var_dump($throwable->getFile());
            var_dump($throwable->getLine());
            var_dump($throwable->getTraceAsString());
        }else{
            $errorMsg = "服务器内部错误";
            var_dump($throwable->getMessage());
            var_dump($throwable->getFile());
            var_dump($throwable->getLine());
        }
        $this->returnData(500,$errorMsg);
        return ;
    }


    /**
     * 获取项目跟目录
     * @return mixed
     */
    public  function getDocumentRootPath(){

        $serverConf = Config::getInstance()->getConf('MAIN_SERVER');

        return $serverConf['SETTING']['document_root'];

    }


    /**
     * 写入日志
     * @param $msg
     * @param array $data
     * @author 品花
     * @date 2019/11/23 0023 下午 2:28
     */
    public static function log($msg,$data=[]){

        Logger::getInstance()->log("$msg:".var_export($data,true),Logger::LOG_LEVEL_INFO,'DEBUG');
    }

    public function getUserIp(){

        return ServerManager::getInstance()->getSwooleServer()->connection_info($this->request()->getSwooleRequest()->fd)['remote_ip']?:"127.0.0.1";
    }



    /** 返回数据
     * @param $code 状态码
     * @param array $data 数据
     * @return string
     */
    public function returnData($code,$data=[],$msg="",$statusCode =200){

        $datas = $data;
        if(in_array("android",$this->request()->getHeaders()['user-agent']) ){
            if (empty($data) && $data !== 0) {
                $datas = new \stdClass();
            } else {
                $datas = new \stdClass();
                $datas->info = $data;
            }
        }

        $data = json_encode([
            'code'=>$code,
            'msg'=> $msg?:\App\Consts\ErrorCode::ERROR_CODE_AND_ERORR_MSG[$code],
            'data'=>$datas
        ]);
        $this->response()->withHeader('Content-type','application/json;charset=utf-8');
        $this->response()->withStatus($statusCode);
        $this->response()->write($data);
        $this->response()->end();
        return ;

    }



    /**
     * 上传文件
     * @param $formKey form->input->name
     * @param string $module 模块
     * @return bool|string
     */
    public function uploadFile($formKey,$module = "system_upload"){

        $uploadConfig = Config::getInstance()->getConf($module);
        $file = $this->request()->getUploadedFile($formKey);
        
        if($file){
            $fileType = $file->getClientMediaType();
            if(!in_array($fileType,$uploadConfig['ext'])){

                throw new \Exception('文件类型不允许');
                return false;
            }
            if($file->getSize() > $uploadConfig['size'] ){

                throw new \Exception('文件太大');
                return false;
            }
            $file_name = md5(date('YmdHis').mt_rand(10000,90000)).'.png';
            $res = $file->moveTo(Config::getInstance()->getConf('MAIN_SERVER.SETTING.document_root').$uploadConfig['path'].$file_name);
            
            return  $file_name;
        }

        return false ;


    }




}